from rest_framework.response import Response
from rest_framework.views import APIView
import sys
from webapi.tools  import * # 引入脚手架php适配工具库

class login( APIView ):
    def post(self, request):
        data = json_decode(request.body.decode())
        account_name = data.get('account_name')
        password = data.get('password')

        if empty(account_name)|empty(password):
            return Response({"status": False,  "message":"请输入完整信息"})
        
        from webapi.model.Admin import Admin # 引入管理员模型

        exist_admin = Admin.objects.filter(account_name=account_name, password=md5(password), is_block=0).first()

        if empty(exist_admin):
            return Response({"status": False,  "message":"账号或者密码错误, 或者已经被冻结"})

        # 记录最后登录时间
        exist_admin.last_login = time()
        exist_admin.save()

        session_arr = {
            "account_name":exist_admin.account_name,
            "password":exist_admin.password,
            "is_super":exist_admin.is_super,
            "proxy_ip":'0.0.0.0', # 用户对应的可用当前代理ip,记录在session中,爬取时当前用户发起的爬虫线程均使用此代理ip
        }

        # 设置seesion
        request.session['ADMIN_SESS'] = json_encode(session_arr)
        request.session.set_expiry(600)

        rep = Response({"status": True, "account_name": exist_admin.account_name, "role_route":"['Order','GOODS','Config','Permission','LittleProgram','Settlement']"})
        
        # 设置cookie
        rep.set_cookie('role_route', "['Order','GOODS','Config','Permission','LittleProgram','Settlement']")
        rep.set_cookie('account_name', exist_admin.account_name)
        rep.set_cookie('is_super_admin', exist_admin.is_super)

        return set_response(rep)

class logout( APIView ):
    def get(self, request):
        request.session.flush()  # 键和值一起清空  # cookie位于客户端无法清空
        return set_response(Response({"status": True}))

    def post(self, request):
        request.session.flush()  # 键和值一起清空  # cookie位于客户端无法清空
        return set_response(Response({"status": True}))